<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 视频
 *
 * @icon fa fa-circle-o
 */
class Avideo extends Backend
{

    /**
     * Avideo模型对象
     * @var \app\admin\model\Avideo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Avideo;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("showstatusList", $this->model->getShowStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $group_id=$this->group_id;
            $where1=null;
            if($group_id==7){
                $where1['avideo.status']='3';
                $admin=session('admin');
                $cate_id=$admin['cate_id'];
                $avideo_ids=cate_avideo($cate_id);


                $c=null;
                $where=null;
                $t=$this->request->param();
                if(isset($t['filter'])){
                    if($t['filter']!='{}'){
                        $c=$t['filter'];
                        $c=json_decode($c, true);
                        $allavideo_ids=$avideo_ids;
                        $xianshiavideo_ids=Db::name('avideo')->where('find_in_set('.$cate_id.',show_ids)')->whereIn('id',$avideo_ids)->column('id');
                        if($c['show_status']=='0'){
                            $avideo_ids=array_diff($allavideo_ids, $xianshiavideo_ids);
                        }elseif ($c['show_status']=='1'){
                            $avideo_ids=$xianshiavideo_ids;
                        }
                    }
                }
                $where1['avideo.id']  = ['in',$avideo_ids];
            }elseif($group_id==6){
                $where1['avideo.status']=['in',['1','2','3']];
            }
            $list = $this->model
                ->with(['category','period','col'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            //查询当前登录后台角色的视频审核权限

            foreach ($list as $row) {

                $row->getRelation('category')->visible(['name']);
                $row->getRelation('period')->visible(['name']);
                $row->getRelation('col')->visible(['name']);
                $row->group_id=$this->group_id;
            }
            $arr=$list->items();
            foreach ($arr as $k=>$v){
                if($group_id==7){
                    $admin=session('admin');
                    $cate_id=$admin['cate_id'];
                    $show_ids=explode(',',$arr[$k]['show_ids']);
                    if(in_array($cate_id,$show_ids)){
                        $arr[$k]['show_status']='1';
                    }else{
                        $arr[$k]['show_status']='0';
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $arr);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
//                    $params['srcfile'] = WEBSITE.$params['srcfile'];
                    $local = ltrim($params['srcfile'],'/');
                    $Ali= new Aliupload();
                    list($re,$time) = $Ali->testUploadLocalVideo($local);
                    if ($re){
                        $params['srcfile'] = $re;
                        $params['duration'] = $time;
                        //删除本地视频文件
                        //unlink($local);
                    }else{
                        $this->error('上传第三方存储失败');
                    }

                    if ($params['image'] != ''){
                        $params['image'] = WEBSITE.$params['image'];
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
//                    if( str_contains($params['srcfile'],'http://') === false && $params['srcfile'] != ''){
//                        $params['srcfile'] = WEBSITE.$params['srcfile'];
//                    }
                    if( str_contains($params['srcfile'],'/uploads') != false ){//如果存在uploads 说明是在上传本地到第三方,调用阿里云osss
                        if ($params['srcfile'] == null){
                            $this->error('请上传视频文件');
                        }
                        $local = ltrim($params['srcfile'],'/');
                        $Ali= new Aliupload();
                        list($re,$time) = $Ali->testUploadLocalVideo($local);
                        if ($re){
                            $params['srcfile'] = $re;
                            $params['duration'] = $time;//视频时长
                            unlink($local);
                        }else{
                            $this->error('上传第三方存储失败');
                        }
                    }

                    if( str_contains($params['image'],'http://') === false && $params['image'] != ''){
                        $params['image'] = WEBSITE.$params['image'];
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /*
     * 申请审批
     * */
    public function applycheck()
    {
        $param = $this->request->param();
        $arr = [
            'id'=>$param['ids'],
            'status'=>'1',
        ];
        $ret = Db::name('avideo')->update($arr);
        if ($ret)$this->success('成功');
        $this->error('失败');
    }

    /*
 * 中级审批员审批拒绝
 * */
    public function nomidcheck()
    {
        $param = $this->request->param();
        $arr = [
            'id'=>$param['ids'],
            'status'=>'2',
        ];
        $ret = Db::name('avideo')->update($arr);
        if ($ret)$this->success('成功');
        $this->error('失败');
    }
    /*
     * 中级审批员审批通过
     * */
    public function midcheck()
    {
        $param = $this->request->param();
        $arr = [
            'id'=>$param['ids'],
            'status'=>'3',
        ];
        $ret = Db::name('avideo')->update($arr);
        if ($ret)$this->success('成功');
        $this->error('失败');
    }
    /*
 *  总管理审批
 * */
    public function fincheck()
    {
        $param = $this->request->param();
        $arr = [
            'id'=>$param['ids'],
            'status'=>'4',
        ];
        $ret = Db::name('avideo')->update($arr);
        if ($ret)$this->success('成功');
        $this->error('失败');
    }
    /*
 *  机场显示审批
 * */
    public function showcheck()
    {
        $ids = $this->request->param('ids');
        $avideo=Db::name('avideo')->where('id',$ids)->find();
        $show_ids=explode(',',$avideo['show_ids']);
        $admin=session('admin');
        $cate_id=$admin['cate_id'];
        if(!in_array($cate_id,$show_ids)){
            $show_ids[]=$cate_id;
            $show_ids=implode(',',$show_ids);
            $arr['show_ids']=$show_ids;
            $ret = Db::name('avideo')->where('id',$ids)->update($arr);
            if ($ret)$this->success('成功');
        }else{
            $this->error('已经显示,请勿重新提交');
        }
    }
    /*
     *  机场隐藏审批
     * */
    public function hiddencheck()
    {
        $ids = $this->request->param('ids');
        $avideo=Db::name('avideo')->where('id',$ids)->find();
        $show_ids=explode(',',$avideo['show_ids']);
        $admin=session('admin');
        $cate_id=$admin['cate_id'];
        if(in_array($cate_id,$show_ids)){
            $k=array_search($cate_id , $show_ids);
            array_splice($show_ids,$k,1);
            $show_ids=implode(',',$show_ids);
            $arr['show_ids']=$show_ids;
            $ret = Db::name('avideo')->where('id',$ids)->update($arr);
            if ($ret)$this->success('成功');
        }else{
            $this->error('失败');
        }
    }
    /*
 *  总管理审批
 * */
    public function nofincheck()
    {
        $param = $this->request->param();
        $arr = [
            'id'=>$param['ids'],
            'status'=>'3',
        ];
        $ret = Db::name('avideo')->update($arr);
        if ($ret)$this->success('成功');
        $this->error('失败');
    }
}
